import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { ModalC, FormGroup, DATA_ENTRY } from '../../../../comps';
import moment from 'moment';
import accounting from 'accounting';
import config from '../../../../comps/business/tradingMarket/config';
import { findValueByCode } from '../../../../utils/utils';
import dictionaryConfig from '../../../../utils/dictionaryConfig';
import _ from 'lodash';
@Form.create()
class positionModal extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      miniUnitId: undefined,
      startDate: '',
      endDate: '',
    };
  }
  componentDidMount() {
    if (['3', '4', '5', '6', '13', '14', '32', '33'].includes(this.props?.modalData?.type)) {
      this.setState({
        startDate: this.props.modalData?.dataDt,
      });
    }
  }

  // 响应上传确定
  onOk = () => {
    const { modalData } = this.props;

    this.formGroupThis.props.form.validateFields((err, fieldsValue) => {
      if (!err) {
        let queryData = fieldsValue;
        queryData.miniUnitId = this.state.miniUnitId; // 产品组合代码
        queryData.compareId = modalData.compareId;
        queryData.operateType = fieldsValue.operateType.toString(); // 调整方向
        queryData.dataDt = modalData.dataDt; // 日期
        queryData.tradingCode = modalData.tradingcode; // 证券代码
        queryData.securityType = modalData.type; // 资产类型
        queryData.exchangeCode = modalData.exchangeCode; // 交易市场
        if (['3', '4', '5', '6', '13', '14', '32', '33'].includes(modalData.type)) {
          queryData.startDate = moment(fieldsValue?.startDate).format('YYYYMMDD'); // 回购起息日
          queryData.endDate = moment(fieldsValue?.endDate).format('YYYYMMDD'); // 回购到期日
        }
        if (fieldsValue.settlementDate) {
          queryData.settlementDate = moment(fieldsValue?.settlementDate).format('YYYYMMDD');
        }
        if (['3', '4', '32', '33'].includes(modalData.type) && modalData.xtsl == 0 && modalData.cwsl != 0) {
          queryData.clearingMethod = '13';
          queryData.orderType = '2';
          queryData.firstSettlementType = '0';
          queryData.settlementType = '0';
        }
        this.props.dispatch({
          type: 'ValuationCheckM/adjustSecurity',
          payload: queryData,
          callback: (data) => {
            if (data) {
              this.props.onOk();
            }
          },
        });
      }
    });
  };

  miniUnitChange = (e) => {
    if (e) {
      this.setState({ miniUnitId: e.info.portfolioCode });
    } else {
      this.setState({ miniUnitId: undefined });
    }
  };
  //获取资产类型的子类别
  getAssetType = (type) => {
    let title;
    let data = dictionaryConfig.holdTypeTree.filter((item) => item.value.split(';').includes(type == '24' ? '23' : type));
    if (data) {
      title = data[0]?.children ? data[0].title + '/' + data[0]?.children.filter((item) => item.value.split(';').includes(type == '24' ? '23' : type))[0]?.title : data[0]?.title;
    }
    return title || '--';
  };

  render() {
    const {
      modalData,
      isVisible,
      loading,
      globalM: {
        dataDictionary: { ENTRUSTED_INVESTMENT_HOLD_ATTRCODE = [] },
      },
    } = this.props;
    let hideFlag = modalData.xtsl == 0 && modalData.cwsl != 0; //系统数量为0，财务数量不为0 情况下新增
    const modalProps = {
      destroyOnClose: true,
      visible: isVisible,
      title: '持仓调平',
      width: 920,
      confirmLoading: loading.effects['ValuationCheckM/adjustSecurity'] === true,
      onCancel: () => {
        this.props.onCancel();
      },
      onOk: () => {
        this.onOk();
      },
    };
    return (
      <ModalC {...modalProps}>
        <div style={{ display: 'flex' }}>
          <div style={{ marginRight: '40px', marginLeft: '30px' }}>
            <span>产品：</span>
            <span>
              {modalData.fundcode}-{modalData.fundname}
            </span>
          </div>
          <div style={{ marginRight: '40px' }}>
            <span>证券：</span>
            <span>
              {modalData.tradingcode}-{modalData.zqName}
            </span>
          </div>
          <div style={{ marginRight: '40px' }}>
            <span>资产类型：</span>
            <span>{this.getAssetType(modalData.type)}</span>
          </div>
          <div style={{ marginRight: '40px' }}>
            <span>交易市场：</span>
            <span>{config.filter((item) => item.selfValue == modalData.exchangeCode)[0]?.title ?? '--'}</span>
          </div>
        </div>
        <div style={{ display: 'flex', marginTop: '15px', marginBottom: '15px' }}>
          <div style={{ marginRight: '40px', marginLeft: '30px' }}>
            <span>系统数量：</span>
            <span>{accounting.formatNumber(Number(modalData.xtsl), 2)}</span>
          </div>
          <div>
            <span>财务数量：</span>
            <span>{accounting.formatNumber(Number(modalData.cwsl), 2)}</span>
          </div>
          <div style={{ marginRight: '40px', marginLeft: '40px' }}>
            <span>差值：</span>
            <span>{accounting.formatNumber(Number(modalData.cz), 2)}</span>
          </div>
          <div>
            <span>交易属性：</span>
            <span>{findValueByCode(modalData.trdAttr, ENTRUSTED_INVESTMENT_HOLD_ATTRCODE)}</span>
          </div>
        </div>
        <div style={{ marginBottom: '15px', paddingLeft: '30px' }}>
          <span>调仓起始日：</span>
          <span>{moment(modalData.dataDt).format('YYYY-MM-DD')}</span>
        </div>
        <FormGroup
          dataSource={[
            {
              title: '产品组合',
              dataIndex: 'miniUnitId',
              type: DATA_ENTRY.PRODUCTGROUPTREE,
              ralation: true,
              productId: modalData?.productId,
              allowClear: true,
              multiple: false,
              onChange: (e) => this.miniUnitChange(e),
              rules: [{ required: true, message: '请选择' }],
              span: 12,
              controlLabelSpan: 6,
            },
            // 当【系统数量】<【财务数量】时，点击“持仓调平”按钮，弹出模态框，【调整方向】不支持“证券减少”；
            {
              title: '调整方向',
              dataIndex: 'operateType',
              type: DATA_ENTRY.SELECT,
              initialValue: 0,
              dataSource:
                ['3', '4', '5', '6', '13', '14', '32', '33'].includes(modalData.type) && modalData.xtsl < modalData.cwsl
                  ? [{ title: '证券增加', value: 0 }]
                  : [
                      { title: '证券增加', value: 0 },
                      { title: '证券减少', value: 1 },
                    ],
              allowClear: true,
              rules: [{ required: true, message: '请选择' }],
              span: 12,
              controlLabelSpan: 6,
              onRef: (ref) => (this.formGroupThis = ref),
            },
            {
              dataIndex: 'amount',
              type: DATA_ENTRY.INPUTNUMBER,
              title: '调整数量',
              min: 0,
              max: 999999999999,
              splitStyle: true,
              rules: [{ required: true, message: '请输入调整数量' }],
              span: 12,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'price',
              type: DATA_ENTRY.INPUTNUMBER,
              title: '成本价',
              min: 0,
              max: 999999999999,
              splitStyle: true,
              rules: [{ required: true, message: '请输入调整成本' }],
              hide: ['0', '7'].includes(modalData.type),
              span: 12,
              controlLabelSpan: 6,
              initialValue: ['3', '4', '32', '33'].includes(modalData.type) ? 100 : undefined,
            },
            {
              dataIndex: 'pricejj',
              type: DATA_ENTRY.INPUTNUMBER,
              title: '净价',
              min: 0,
              max: 999999999999,
              splitStyle: true,
              rules: [{ required: true, message: '请输入净价' }],
              hide: !['0', '7'].includes(modalData.type),
              span: 12,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'priceqj',
              type: DATA_ENTRY.INPUTNUMBER,
              title: '全价',
              min: 0,
              max: 999999999999,
              splitStyle: true,
              rules: [{ required: true, message: '请输入全价' }],
              hide: !['0', '7'].includes(modalData.type),
              span: 12,
              controlLabelSpan: 6,
            },
            {
              title: '清算类型',
              dataIndex: 'liquidationType',
              type: DATA_ENTRY.SELECT,
              dataSource: [
                { title: '自行清算', value: '13' },
                { title: '集中清算', value: '6' },
              ],
              initialValue: '13',
              multiple: false,
              hide: !(['0'].includes(modalData.type) && ['B'].includes(modalData.exchangeCode) && hideFlag),
              rules: [{ required: true, message: `请选择清算类型` }],
              placeholder: '请选择',
              span: 12,
              controlLabelSpan: 6,
            },
            {
              title: '清算速度',
              dataIndex: 'settlementSpeed',
              type: DATA_ENTRY.SELECT,
              dataSource: [
                { title: 'T+0', value: '1' },
                { title: 'T+1', value: '2' },
              ],
              initialValue: '1',
              hide: !(['0'].includes(modalData.type) && ['B'].includes(modalData.exchangeCode) && hideFlag),
              rules: [{ required: true, message: '请选择清算速度!' }],
              multiple: false,
              placeholder: '请选择',
              span: 12,
              controlLabelSpan: 6,
            },
            {
              title: '结算日期',
              dataIndex: 'settlementDate',
              type: DATA_ENTRY.SINGLEDATE,
              // onChange: e => this.changeDate(e),
              hide: !(['0'].includes(modalData.type) && ['B'].includes(modalData.exchangeCode) && hideFlag),
              rules: [{ required: true, message: `请选择结算日期` }],
              initialValue: ['B'].includes(modalData.exchangeCode) ? moment(modalData.dataDt) : undefined,
              span: 12,
              controlLabelSpan: 6,
            },
            {
              title: '对手交易员',
              dataIndex: 'opponentTrading',
              type: DATA_ENTRY.INPUT,
              hide: !(['0'].includes(modalData.type) && ['B'].includes(modalData.exchangeCode) && hideFlag),
              placeholder: '请输入',
              span: 12,
              controlLabelSpan: 6,
            },
            {
              title: '分红方式',
              dataIndex: 'dividendMethod',
              type: DATA_ENTRY.SELECT,
              dataSource: [
                { title: '现金分红', value: '1' },
                { title: '红利再投', value: '2' },
              ],
              allowClear: true,
              hide: !(['2'].includes(modalData.type) && hideFlag),
              rules: [{ required: true, message: '请选择' }],
              span: 12,
              controlLabelSpan: 6,
            },

            // {
            //     title: '首期结算日期',
            //     type: DATA_ENTRY.SINGLEDATE,
            //     dataIndex: 'startDate',
            //     rules: [{ required: true, message: '请选择首期结算日期' }],
            //     hide: !(['3', '4'].includes(modalData.type) && hideFlag),
            //     disableEnd: moment(this.state.endDate).add(1, 'days'),
            //     onChange: (e) => { this.setState({ startDate: e }) },
            //     span: 12,
            //     controlLabelSpan: 6
            // },
            // {
            //     title: '到期结算日期',
            //     type: DATA_ENTRY.SINGLEDATE,
            //     dataIndex: 'endDate',
            //     rules: [{ required: true, message: '请选择到期结算日期' }],
            //     hide: !(['3', '4'].includes(modalData.type) && hideFlag),
            //     disableBegin: moment(this.state.startDate).subtract(1, 'days'),
            //     onChange: (e) => { this.setState({ endDate: e }) },
            //     span: 12,
            //     controlLabelSpan: 6
            // },
            {
              title: '回购利率',
              dataIndex: 'repoRate',
              placeholder: '请输入',
              type: DATA_ENTRY.INPUTNUMBER,
              precision: 2,
              min: 0,
              splitStyle: true,
              hide: !['3', '4', '5', '6', '32', '33'].includes(modalData.type),
              max: 100,
              rules: [{ required: true, message: `请输入回购利率` }],
              unit: '%',
              span: 12,
              controlLabelSpan: 6,
            },
            {
              // 交易对手
              dataIndex: 'counterparty',
              type: DATA_ENTRY.TRADINGCOMPANY,
              multiple: false,
              placeholder: '请选择',
              rules: [{ required: true, message: '请输入交易对手!' }],
              hide: !['3', '4', '32', '33'].includes(modalData.type),
              span: 12,
              controlLabelSpan: 6,
            },
            {
              title: '清算速度',
              dataIndex: 'settlementSpeed',
              type: DATA_ENTRY.SELECT,
              dataSource: [
                { title: 'T+0', value: '1' },
                { title: 'T+1', value: '2' },
              ],
              initialValue: '1',
              hide: !['3', '4', '32', '33'].includes(modalData.type),
              rules: [{ required: true, message: '请选择清算速度!' }],
              multiple: false,
              placeholder: '请选择',
              span: 12,
              controlLabelSpan: 6,
            },
            {
              title: '首期结算日期',
              type: DATA_ENTRY.SINGLEDATE,
              dataIndex: 'startDate',
              rules: [{ required: true, message: '请选择首期结算日期' }],
              hide: !['3', '4', '5', '6', '13', '14', '32', '33'].includes(modalData.type),
              disableEnd: moment(this.state.endDate).add(1, 'days'),
              initialValue: moment(modalData.dataDt),
              onChange: (e) => {
                this.setState({ startDate: e });
              },
              span: 12,
              controlLabelSpan: 6,
            },
            {
              title: '到期结算日期',
              type: DATA_ENTRY.SINGLEDATE,
              dataIndex: 'endDate',
              rules: [{ required: true, message: '请选择到期结算日期' }],
              hide: !['3', '4', '5', '6', '13', '14', '32', '33'].includes(modalData.type),
              disableBegin: moment(this.state.startDate).subtract(1, 'days'),
              onChange: (e) => {
                this.setState({ endDate: e });
              },
              span: 12,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'remark',
              type: DATA_ENTRY.INPUT,
              title: '备注',
              placeholder: '请输入',
              showTextArea: true,
              autosize: { minRows: 2, maxRows: 2 },
              span: 24,
              controlLabelSpan: 3,
            },
          ]}
          autoLayout={false}
        />
      </ModalC>
    );
  }
}
export default connect(({ ValuationCheckM, loading, globalM }) => ({ ValuationCheckM, loading, globalM }))(positionModal);
